import { createRouter, createWebHashHistory,RouteRecordRaw } from 'vue-router'
import useStore from '../store/index'
const routes: Array<RouteRecordRaw> = [
  {
    path: '/401',
    component: () => import('../views/401.vue')
  },
  {
    path: '/404',
    component: () => import('../views/404.vue')
  },
  {
    path:'/login',
    component: () => import('../views/login.vue')
  }
]

// 白名单
const whiteList:Array<string> = ['/login', '/404', '/401']
let flag:boolean = true

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next)=>{
  const token = localStorage.getItem('token')
  if(token) {
    if(to.path === '/login'){
      next({path:'/'})
    }else {
      if(flag){
        const UseUserStore = useStore()
        if(!UseUserStore.user.menu.length){
          //表示没有菜单列表
          localStorage.removeItem('token')
					router.push('/login')
				}else {
          flag = false       
          //解决刷新页面路由消失的问题 
          UseUserStore.user.setRouters()
          UseUserStore.user.setUserRouter().then((res:any)=>{
            res.forEach((element:RouteRecordRaw) => {
              router.addRoute(element)
            });
          })
          next({ ...to, replace: true })
        }        
      }else {
        next()
      }
    }
  }else {
    if (whiteList.includes(to.path)) {
			// 在白名单内，放行
			next()
		} else {
			// 否则全部重定向到登录页
			next('/login')
		}
  }
})

//导出router
export default router